import { Injectable } from '@nestjs/common';
import { CreateRolePermissionDto } from './dto/create-role-permission.dto';
import { UpdateRolePermissionDto } from './dto/update-role-permission.dto';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { RolePermission } from './entities/role-permission.entity';
import { RoleMenu } from './entities/role-menu.entity';
import { responseData } from '../common/response.handle';
import { MenuItem } from 'src/menu/menu.interface';

@Injectable()
export class RolePermissionService {
	constructor(
		@InjectRepository(RolePermission)
		private rolePermissionRepository: Repository<RolePermission>,
		@InjectRepository(RoleMenu)
		private roleMenuRepository: Repository<RoleMenu>,
		@InjectDataSource()
		private dataSource: DataSource,
	) {}

	async grantPermissionsToRole(createRolePermissionDto: CreateRolePermissionDto) {
		// this.rolePermissionRepository.c;
		await this.dataSource.transaction(async (transactionalEntityManager) => {
			// execute queries using transactionalEntityManager
			const rolePermissionRepository = await transactionalEntityManager.getRepository(RolePermission);
			const roleMenuRepository = await transactionalEntityManager.getRepository(RoleMenu);
			// 1、先删除原本的权限
			await rolePermissionRepository.delete({
				roleId: createRolePermissionDto.roleId,
			});
			// 2、添加新的权限
			const addPermissions = createRolePermissionDto.permissionIds.map((item) => {
				return {
					roleId: createRolePermissionDto.roleId,
					permissionId: item,
				};
			});
			await rolePermissionRepository.save(addPermissions);

			// 3、先删除原本的菜单权限
			await roleMenuRepository.delete({
				roleId: createRolePermissionDto.roleId,
			});
			// 2、添加新的菜单权限
			const addMenus = createRolePermissionDto.menuIds.map((item) => {
				return {
					roleId: createRolePermissionDto.roleId,
					menuId: item,
				};
			});
			await roleMenuRepository.save(addMenus);
		});
		return responseData(null, '分配权限成功');
	}

	async findRolePermissionsMenus(roleId: number) {
		// this.rolePermissionRepository.c;
		// 1、先查询权限信息
		const permissions = await this.rolePermissionRepository
			.createQueryBuilder('rolePermission')
			.leftJoinAndSelect('rolePermission.permission', 'permission')
			.where({ roleId })
			.getMany();

		// 2、再查询菜单信息
		const menus = await this.roleMenuRepository
			.createQueryBuilder('roleMenu')
			.leftJoinAndSelect('roleMenu.menu', 'menu')
			.where({ roleId })
			.getMany();
		return responseData(
			{
				menus: menus.map((item) => item.menu),
				permissions: permissions.map((item) => item.permission),
			},
			'查询权限菜单列表成功',
		);
	}

	async findRolePermissions(roleId: number) {
		// this.rolePermissionRepository.c;

		// 1、先查询权限信息
		const permissions = await this.rolePermissionRepository
			.createQueryBuilder('rp')
			.leftJoinAndSelect('rp.permission', 'permission')
			.where({ roleId })
			.getMany();
		// const permissions = await this.rolePermissionRepository.find();
		// console.log(permissions);
		const rows = permissions.map((item) => item.permission);
		return responseData(rows, '查询角色权限列表成功');
	}

	async findRoleMenus(roleId: number) {
		// this.rolePermissionRepository.c;
		// 1、先查询权限信息
		// 2、再查询菜单信息
		const menus = await this.roleMenuRepository
			.createQueryBuilder('roleMenu')
			.leftJoinAndSelect('roleMenu.menu', 'menu')
			.where({ roleId })
			.getMany();

		console.log(menus);
		// 将所有菜单项存储在一个对象中，其中键为菜单项的ID
		const menuItemsById: { [key: number]: MenuItem } = menus
			.map((item) => item.menu)
			.reduce((acc, menuItem) => {
				acc[menuItem.id] = menuItem;
				return acc;
			}, {}) as MenuItem[];

		// 创建一个空数组，用于存储根菜单项
		const rootMenuItems: MenuItem[] = [];

		// 将每个菜单项添加到其父级菜单项的“children”数组中
		menus
			.map((item) => item.menu)
			.forEach((menuItem: MenuItem) => {
				if (menuItem.parentId === null) {
					// 如果该菜单项没有父级，则将其视为根级别菜单项
					rootMenuItems.push(menuItem);
				} else {
					// 否则，将该菜单项作为其父级的子项，并将其添加到父级菜单项的“children”数组中
					const parentMenuItem = menuItemsById[menuItem.parentId];
					if (!parentMenuItem?.children) {
						parentMenuItem['children'] = [];
					}
					parentMenuItem.children.push(menuItem);
				}
			});
		return responseData(rootMenuItems, '查询角色菜单列表成功');
	}

	create(createRolePermissionDto: CreateRolePermissionDto) {
		// this.rolePermissionRepository.c;
		return 'This action adds a new rolePermission';
	}

	findAll() {
		return `This action returns all rolePermission`;
	}

	findOne(id: number) {
		return `This action returns a #${id} rolePermission`;
	}

	update(id: number, updateRolePermissionDto: UpdateRolePermissionDto) {
		return `This action updates a #${id} rolePermission`;
	}

	remove(id: number) {
		return `This action removes a #${id} rolePermission`;
	}
}
